// Copyright (c) Microsoft Corporation and Contributors.
// Licensed under the MIT License.

using System;
using System.Threading.Tasks;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using WeAppsCenter.Controls;
using WeAppsCenter.Core;

// To learn more about WinUI, the WinUI project structure,
// and more about our project templates, see: http://aka.ms/winui-project-info.

namespace WeAppsCenter.Pages;
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Update : Page
{
    public Update()
    {
        this.InitializeComponent();
        Refresh_Click(null, null);
    }

    public async void Refresh_Click(object sender, RoutedEventArgs e)
    {
        refresh.IsEnabled = false;
        AppsToUpdate.Children.Clear();
        var task = Task.Run(() =>
        {
            WeGet.Apps apps = new WeGet.Apps(Core.Settings.DataDirectory);
            apps.Update();
        });
        await task.WaitAsync(TimeSpan.FromSeconds(120));


        mainWindow.ChangeInfoBadge();

        PresentUpdates();
        refresh.IsEnabled = true;

    }
    private void PresentUpdates()
    {
        CheckForApplicationUpdates checkForUpdates = new CheckForApplicationUpdates();


        foreach (var packageName in checkForUpdates.GetUpdates())
        {
            GetAppInfo getAppInfo = new GetAppInfo();
            AppInfo appInfo = getAppInfo.GetAppInfoByPackageName(packageName);
            AppsToUpdate.Children.Add(new UpdatePresenter(appInfo) { update = this });
        }
        if (AppsToUpdate.Children.Count == 0)
        {
            UpToDate upToDate = new UpToDate();
            AppsToUpdate.Children.Add(upToDate);
        }

    }

    public MainWindow mainWindow = (MainWindow)App.m_window;
}
